package com.wiscamp.ninechapters.problems.adapter.resources.sheets;

import com.wiscamp.ninechapters.problems.application.dto.commands.sheets.SubmitSheetCommand;
import com.wiscamp.ninechapters.problems.application.dto.vo.sheets.SheetVO;
import com.wiscamp.ninechapters.problems.application.services.SheetAppService;
import cube.ddd.adapter.BaseController;
import cube.ddd.adapter.RestResponse;
import cube.ddd.aspect.HandleResourceException;
import cube.ddd.utils.ResourceUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.core.Context;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * 答题卡服务端点
 *
 * @author yifeng
 */
@RestController
@RequestMapping("/api/Problems")

@Tag(name = "题库-答题卡信息")
public class SheetController extends BaseController {

    private final SheetAppService sheetAppService;

    public SheetController(SheetAppService sheetAppService) {
        this.sheetAppService = sheetAppService;
    }

    /**
     * 通过答题卡编号获取答题卡
     *
     * @param request
     * @param response
     * @param sheetId
     * @return
     */
    @GetMapping("Sheets/{sheetId}")
    @Operation(summary = "通过答题卡编号获取答题卡")
    @HandleResourceException
    public RestResponse<SheetVO> getSheet(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                          @PathVariable("sheetId") long sheetId) {
        return ResourceUtils.getById(request, response, sheetId, sheetAppService::getSheet);
    }

    /**
     * 通过用户编号获取答题卡列表
     *
     * @param userId
     * @return 习题集答题卡列表
     */
    @GetMapping("Users/{userId}/Sheets")
    @Operation(summary = "通过用户编号获取答题卡列表")
    @HandleResourceException
    public RestResponse<Collection<SheetVO>> getSheetsByUser(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                                             @PathVariable("userId") long userId) {
        return ResourceUtils.getListById(request, response, userId, sheetAppService::getSheetsByUser);
    }


    /**
     * 创建答题卡
     *
     * @param sheet
     * @return
     */
    @PostMapping("Sheets")
    @Operation(summary = "提交答题卡")
    @HandleResourceException
    public RestResponse<SheetVO> submitSheet(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                             @RequestBody SubmitSheetCommand command) {
        //var json = JsonUtils.toJson(command);
        //String file = command.getTaskId() + "." + CodeHelper.get62RadixDateTime() + ".json";
        //IOHelper.writeTextFile(json, file, false);
        var newSheet = sheetAppService.submitSheet(command);
        return ResourceUtils.getOkResponse(request, response, newSheet);
    }
}
